package com.fay.basic.base.copy;

import lombok.Data;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/5/10 15:55
 * @Version 1.0
 */
public class CopyTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        Family family = new Family();
        family.setName("Fay's Family");
        Student s1 = new Student();
        s1.setFamily(family);
        s1.setName("Fay");

        Student s2 = (Student) s1.clone();
        s2.setName("Jack");
        s2.getFamily().setName("Jack's Family");
        System.out.println("old student:" + s1.getName() + " And old family:" + s1.getFamily().getName());
        System.out.println("new student:" + s2.getName() + " And new family:" + s2.getFamily().getName());

    }

}

@Data
class Family implements Cloneable {
    private String name;

    @Override
    protected Object clone() {
        Family o = null;
        try {
            o = (Family) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return o;
    }
}

@Data
class Student implements Cloneable {
    private String name;
    private Family family;

    /**
     * 浅拷贝，对其对象的引用，并没有创建
     * @return
     * @throws CloneNotSupportedException
     *//*
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }*/

    @Override
    protected Object clone()  {
        Student o = null;
        try {
            o = (Student) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        o.family = (Family) family.clone();
        return o;
    }
}
